﻿using CHSystemApi.Framework.DataAccess;
using CHSystemApi.DataAccess.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System.Collections.Generic;
using System.Data.Common;


namespace CHSystemApi.DataAccess
{
    public class DataContext : DbContext, IDataAccess
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }

        protected DbConnection _connection
        {
            get
            {
                return base.Database.GetDbConnection();
            }
        }

        public DbSet<User> User { get; set; }

        public DbSet<Permission> Permission { get; set; }

        public DbSet<PermissionGroup> PermissionGroup { get; set; }

        public DbSet<PermissionAssignment> PermissionAssignment { get; set; }

        public DbSet<PermissionGroupRule> PermissionGroupRule { get; set; }

        public DataContext Context { get { return this; } }

        public DbTransaction BeginTransaction()
        {
            if (_connection.State != System.Data.ConnectionState.Open)
                _connection.Open();
            DbTransaction transaction = base.Database.CurrentTransaction?.GetDbTransaction();
            if (transaction != null)
                return transaction;
            transaction = _connection.BeginTransaction();
            base.Database.UseTransaction(transaction);
            return transaction;
        }
    }
}
